package org.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileSyncServer2 {
    public static void main(String[] args) {
        // 监听的端口号
        int serverPort = 1234;

        try {
            // 创建ServerSocket并监听指定端口
            ServerSocket serverSocket = new ServerSocket(serverPort);

            System.out.println("服务端已启动，等待连接...");

            // 接受客户端连接请求
            Socket clientSocket = serverSocket.accept();

            // 获取客户端输入流，并读取请求
            InputStream inputStream = clientSocket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String request = reader.readLine();

            // 解析请求，提取要删除的文件名
            String[] requestParts = request.split(" ");
            String deleteFileName = requestParts[1];

            // 删除文件
            deleteFile(deleteFileName);

            System.out.println("服务端成功删除文件: " + deleteFileName);

            // 关闭连接
            clientSocket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void deleteFile(String fileName) {
        String serverDirectory = "D:\\clouder\\server";
        String serverFilePath = serverDirectory + "/" + fileName.substring(fileName.lastIndexOf("\\"));

        try {
            // 在服务端删除相同的文件
            Path serverPath = Paths.get(serverFilePath);
            Files.deleteIfExists(serverPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
